const express = require('express')
const fetch = require('isomorphic-unfetch')
const mulan = require('mulan-lib')
const config = require('./config')
const crypto = require('crypto')

const { stringifyQuery } = mulan
const PORT = 8088

const { appid, appsecret, ticket_src } = config

const defCharArray = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

const randomString = (length, chars) => {
  let result = '';
  for (let i = length; i > 0; --i) {
      result += chars[Math.round(Math.random() * (chars.length - 1))]
  }
  return result
}

const server =
express()
.get(('/ticket'), (req, res) => {
  const { url } = req.query

  const token_url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${ appid }&secret=${ appsecret }`

  fetch(token_url).then(r => r.json()).then(reply => {
    console.log(reply)

    const { data } = reply
    // const { token: access_token } = data
    const { access_token } = reply

    if (access_token) {
      const ticket_param = {
        access_token,
        type: 'jsapi'
      }
      const ticket_url = `${ ticket_src }${ stringifyQuery(ticket_param) }`
      fetch(ticket_url).then(r => r.json()).then(reply2 => {

        const { ticket } = reply2

        const param = {
          jsapi_ticket: ticket,
          noncestr: randomString(16, defCharArray),
          timestamp: parseInt(Date.now() / 1000),
          url,
        }

        const baseStr = unescape(stringifyQuery(param).substr(1))
        const sha1 = crypto.createHash('sha1');

        sha1.update(baseStr);

        const hash = sha1.digest('hex');
        param.signature = hash

        res.json({
          code: 0,
          msg: 'success',
          data: {
            config: {
              appId: appid,
              nonceStr: param.noncestr,
              timestamp: param.timestamp,
              signature: param.signature,
            }
          }
        })
      }).catch(e => {
        console.log('获取ticket失败', e)
      })
    }
  }).catch(e => {
    console.log('获取access_token失败', e)
  })
})

server.listen(PORT, () => {
  console.log('server run at:', PORT)
})
